<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\DrainageLink\Action\Dashboard;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkContract;

/**
 * 引流链接 - 修改.
 *
 * Class Update.
 * @Controller
 */
class Update extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var DrainageLinkContract
     */
    protected $drainageLink;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/drainageLink/update", methods="put")
     * @return array 返回数组
     * @throws \Exception
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }

        // 参数验证
        $params = $this->request->all();
        $this->validated($params, 'update');

        // 校验重复
        if (! empty($this->drainageLink->getDrainageLinkListByCorpIdName($user['corpIds'][0], $params['name'], (int) $params['id']))) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '渠道引流链接名称重复，不可操作');
        }
        // 处理参数
        $data = $this->handleParam($params);
        // 创建链接
        $id = $this->updateDrainageLink((int) $params['id'], $data);

        return [$id];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'id' => 'required|integer|min:1|bail',
            'type' => 'required|integer|min:1|bail',
            'name' => 'required',
            'pageTitle' => 'required',
            'pageType' => 'required|integer|min:1|bail',
            'corpName' => 'required',
            //            'corpLogo' => 'required',
            'guideText' => 'required',
            'corpNicknameStatus' => 'required',
            'corpMobileStatus' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'id.required' => 'id 必传',
            'type.required' => '类型 必传',
            'name.required' => '链接名称 必传',
            'pageTitle.required' => '页面标题 必传',
            'pageType.required' => '页面样式 必传',
            'corpName.required' => '企业名称 必传',
            //            'corpLogo.required' => '企业logo 必传',
            'guideText.required' => '引导文案 必传',
            'corpNicknameStatus.required' => '企业电话状态 必传',
            'corpMobileStatus.required' => '企业昵称状态 必传',
        ];
    }

    /**
     * 处理参数.
     * @param array $params 接受参数
     * @return array 响应数组
     */
    private function handleParam(array $params): array
    {
        // 基本信息
        return [
            'type' => (int) $params['type'],
            'name' => $params['name'],
            'qrcode_id' => $params['qrcodeId'] ?? 0,
            'qrcode_type' => $params['qrcodeType'] ?? 0,
            'qrcode' => $params['qrcode'] ?? '',
            'page_title' => $params['pageTitle'],
            'page_type' => (int) $params['pageType'],
            'corp_name' => $params['corpName'],
            'corp_logo' => $params['corpLogo'],
            'corp_mobile_status' => $params['corpMobileStatus'],
            'corp_mobile' => $params['corpMobile'] ?? '',
            'corp_nickname_status' => $params['corpNicknameStatus'],
            'corp_nickname' => $params['corpNickname'] ?? '',
            'corp_avatar' => $params['corpAvatar'] ?? '',
            'guide_text' => $params['guideText'],
            'is_statistic' => $params['isStatistic'] ?? 0,
            'is_login' => $params['isLogin'] ?? 0,
        ];
    }

    /**
     * 修改引流链接.
     * @param array $params 参数
     * @return int 响应数值
     */
    private function updateDrainageLink(int $id, array $params): int
    {
        // 数据操作
        Db::beginTransaction();
        try {
            // 创建活动
            $id = $this->drainageLink->updateDrainageLinkById($id, $params);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '引流链接修改失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
        return $id;
    }
}
